﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Configuration.Provider;
using System.Web.Configuration;

namespace Intergr8.Data
{
    /// <summary>
    /// The data provider manager class
    /// </summary>
    /// <remarks>
    /// The main purpose of the data provider manager is to initialize a concrete provider 
    /// and load user configuration settings in memory.
    /// </remarks>
    public class DataProviderManager
    {
        /// <summary>
        /// Instance of a DataProvider object
        /// </summary>
        private static DataProvider defaultProvider;
        /// <summary>
        /// Instance of a DataProviderCollection object
        /// </summary>
        private static DataProviderCollection providers;

        /// <summary>
        /// Default constructor
        /// </summary>
        static DataProviderManager()
        {
            Initialize();
        }

        /// <summary>
        /// Initialisation
        /// </summary>
        /// <remarks>
        /// Invokes initialisation of the provider from the configuration file.
        /// </remarks>
        private static void Initialize()
        {
            // Obtain a pointer to the configuration section
            DataProviderConfiguration configuration =
                (DataProviderConfiguration)
                ConfigurationManager.GetSection("DataProvider");

            // Throw an error if its missing
            if (configuration == null)
                throw new ConfigurationErrorsException
                    ("DataProvider configuration section is not set correctly.");

            // Create a collection to hold the providers
            providers = new DataProviderCollection();

            // Instantiate the configured providers
            ProvidersHelper.InstantiateProviders(configuration.Providers
                , providers, typeof(DataProvider));

            // Mark these as read only.
            providers.SetReadOnly();

            defaultProvider = providers[configuration.Default];

            if (defaultProvider == null)
                throw new Exception("defaultProvider");
        }

        /// <summary>
        /// Access to the provider instance
        /// </summary>
        public static DataProvider Provider
        {
            get
            {
                return defaultProvider;
            }
        }

        /// <summary>
        /// Access to the provider collection
        /// </summary>
        public static DataProviderCollection Providers
        {
            get
            {
                return providers;
            }
        }
    }
}
